package com.iot.core.sender;

import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.iot.model.v20180120.PubRequest;
import com.iot.core.base.IotConstant;
import com.iot.core.base.IotConnectParam;
import lombok.AllArgsConstructor;
import lombok.Getter;

import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;
import java.util.Base64;

/**
 * @auther 王霄
 * @date 2022/7/26 14:43
 */
@AllArgsConstructor
@Getter
public class IotDefaultSender implements IotSender {
    private final IAcsClient iAcsClient;
    private final IotConnectParam iotConnectParam;

    @Override
    public void send(String deviceName, int qos, String payload) throws ClientException {
        PubRequest request = new PubRequest();
        request.setQos(qos);
        request.setIotInstanceId(iotConnectParam.getIotInstanceId());
        request.setTopicFullName(MessageFormat.format(IotConstant.TOPIC_TO_DEVICE, iotConnectParam.getProductKey(), deviceName));
        request.setProductKey(iotConnectParam.getProductKey());
        request.setMessageContent(Base64.getEncoder().encodeToString(payload.getBytes(StandardCharsets.UTF_8)));
        iAcsClient.getAcsResponse(request);
    }
}
